module.exports = function($scope, $modalInstance, $resource, product, $q, $http){

	console.log('memberlevelcommission');

	$scope.product = product;

	
	function load(){

		var beforedata = {
			//级别列表
			'memberlevellist':
			$http({
				'method': 'GET',
				'url': '/api/as/uc/userwxsk/memberlevellist',
			}),
			//产品佣金
			'productprofitlist':
			$http({
				'method': 'GET',
				'url': '/api/as/wc/productprofit/productprofitlist',
				'params': { 'product_code': product.code },
			}),
			
		};


		$q.all(beforedata).then(function (res) {

			console.log(res);

			//级别列表
			if (res.memberlevellist.data.errcode === 0) {
			} else {
				alert('/api/as/uc/userwxsk/memberlevellist' + res.memberlevellist.data.errmsg);
				return;
			}

			//佣金列表
			if (res.productprofitlist.data.errcode === 0) {
			} else {
				alert('/api/as/wc/productprofit/productprofitlist' + res.productprofitlist.data.errmsg);
				return;
			}

			console.log(res.productprofitlist.data.data);

			var levelarr = res.memberlevellist.data.data;
			var commissionarr = res.productprofitlist.data.data;

			for(var i = 0; i < levelarr.length; i++){
				var level = levelarr[i];
				level['profit'] = 0;
				level['profit1'] = 0;
				level['profit2'] = 0;
				level['state'] = 0;

				for(var j = 0; j < commissionarr.length; j++){
					var commission = commissionarr[j];
					if(level.code == commission.level_code){
						level['profit'] = commission.profit;
						level['profit1'] = commission.profit1;
						level['profit2'] = commission.profit2;												
						level['state'] = commission.state;
						level['id'] = commission.id;
						break;
					}
				}
			}

			$scope.objs = levelarr;

		});

	}
	load();


	$scope.opt = function(obj){
		console.log(obj);

		var para = {
			'level_code' : obj.code,
			'code' : product.code,
			'profit' : obj.profit,
			'profit1' : obj.profit1,
			'profit2' : obj.profit2,
			'state' : obj.state == '1' ? '0' : '1',
		};

		if(angular.isDefined(obj.id)){
			para['id'] = obj.id;
		}

		$resource('/api/ac/wc/productService/createProductProfit', {}, {}).save(para, function (res) {
			console.log(para);
			console.log(res);

			if (res.errcode !== 0) {
				alert("数据获取失败");
				return;
			}

			load();

		});


	}

	$scope.save = function(obj){

		var para = {
			'level_code' : obj.code,
			'code' : product.code,
			'profit' : obj.profit,
			'profit1' : obj.profit1,
			'profit2' : obj.profit2,			
			'state' : '1',
		}

		if(angular.isDefined(obj.id)){
			para['id'] = obj.id;
		}

		$resource('/api/ac/wc/productService/createProductProfit', {}, {}).save(para, function (res) {
			console.log(para);
			console.log(res);

			if (res.errcode !== 0) {
				alert(res.errmsg);
				return;
			}

			load();

		});

	}


	$scope.cancel = function () {
        $modalInstance.close();
    }

};